import { getToken } from '@/utils/auth';
import { formatDate } from '@/utils';
import { clearUnread } from '@/api/mall/chat';
import { Message } from 'element-ui';
const ws = {
	namespaced: true,
	state: {
		ws: {},
		loading: false,
		webSocketState: false,
		number: 0,
		//查询今日接待
		isToday: null,
		//实时消息数量
		unreadMessage: 0,
		//发送Index,
		sendIndex: 0,
	},
	mutations: {
		CONNECT(state, ws) {
			state.ws = ws;
		},
		LOADING(state, loading) {
			state.loading = loading;
		},
		GET_LIST(state) {
			const data = {
				msg: '',
				userId: this.getters.userId,
				nickName: this.getters.kfInfo.name || this.getters.name,
				photo: this.getters.kfInfo.headUrl || this.getters.avatar,
				type: 1,
				msgType: 1,
				joinUserId: null,
				operationType: 1,
				isToday: state.isToday,
				sendTime: formatDate(new Date()),
			};
			setTimeout(() => {
				state.ws.send(JSON.stringify(data));
				state.ws.send(
					JSON.stringify({
						msg: '',
						userId: this.getters.userId,
						nickName: this.getters.kfInfo.name || this.getters.name,
						photo: this.getters.kfInfo.headUrl || this.getters.avatar,
						type: 1,
						msgType: 1,
						joinUserId: null,
						operationType: 5,
						isToday: state.isToday,
						sendTime: formatDate(new Date()),
					})
				);
			}, 0);
		},
	},
	actions: {
		//连接ws
		connect({ commit, state }) {
			const url = process.env.VUE_APP_CHAT_API + '/web-socket/' + this.getters.userId + '?token=' + getToken();
			console.log('url', url);
			commit('LOADING', true);
			commit('CONNECT', new WebSocket(url));
			// state.ws = new WebSocket(url);
			state.ws.onopen = () => {
				console.log('连接聊天室成功');
				commit('LOADING', false);
				commit('GET_LIST');
				this.dispatch('ws/startHeartBeat', 5000);
			};
			state.ws.onmessage = (event) => {
				const obj = JSON.parse(event.data);
				if (obj.operationType === 1) {
					let arr = obj.operationParam;
					console.log(arr, 'arr');
					this.dispatch(
						'chat/getChatlist',
						arr.map((item, index) => ({
							id: item.joinUserId,
							unreadMessage: item.unreadMessage,
							user: {
								name: item.nickName,
								img: item.avatar !== '' ? item.avatar : require('@/assets/images/tx_02.jpg'),
							},
							messages: [
								{
									content: item.newMsg,
									date: item.newMsgTime,
								},
							],
							time: item.newMsgTime,
							index: index + 1,
							msgType: item.newMsgType,
							content: item.newMsg,
						}))
					);
					setTimeout(() => {
						if (!this.selectId) return;
						this.dispatch('chat/selectSession', this.selectId);
					}, 1000);
					return;
				} else if (obj.operationType === 3) {
					console.log('接受心跳响应-----');
					state.webSocketState = true;
					return;
				} else if (obj.operationType === 4) {
					console.log('添加会话成功-----');
					Message.success('添加会话成功');
					commit('GET_LIST');
					return;
				} else if (obj.operationType === 5) {
					console.log('收到实时消息数量-----');
					state.unreadMessage = obj.unreadMessage;
					return;
				} else {
					if (obj.userId === this.selectId && this.selectId) {
						clearUnread(this.selectId).then(() => {
							commit('GET_LIST');
						});
					} else {
						commit('GET_LIST');
					}

					setTimeout(() => {
						if (!this.selectId) return;
						this.dispatch('chat/selectSession', this.selectId);
					}, 1000);
				}
				obj.self = false;
				this.dispatch('chat/sendMessage', obj);
			};
			state.ws.onclose = (event) => {
				state.webSocketState = false;
				if (state.number >= 5) {
					return;
				}
				setTimeout(() => {
					state.number += 1;
					this.dispatch('ws/connect');
					//重连操作
				}, 1000);
				console.log('Connection closed.', event.code + ',' + event.reason);
			};
		},
		//发送
		send({ state }, data) {
			state.ws.send(data);
		},
		/*
		 * 心跳初始函数
		 * @param time：心跳时间间隔
		 */
		startHeartBeat(time) {
			console.log('发送心跳-------');
			setTimeout(() => {
				const obj = {
					msg: '',
					userId: this.getters.userId,
					nickName: this.getters.name,
					photo: this.getters.avatar,
					type: 1,
					msgType: 1,
					joinUserId: null,
					operationType: 3,
					sendTime: formatDate(new Date()),
				};
				this.dispatch('ws/send', JSON.stringify(obj));
				this.dispatch('ws/waitingServer', 30000);
			}, time);
		},
		//延时等待服务端响应，通过webSocketState判断是否连线成功
		waitingServer({ state }, time) {
			setTimeout(() => {
				if (state.webSocketState) {
					this.dispatch('ws/startHeartBeat', time);
					return;
				}
				console.log('心跳无响应，已断线');
				//重连操作
			}, time);
		},
		updateIsDay({ state, commit }, num) {
			state.isToday = num;
			setTimeout(() => {
				commit('GET_LIST');
			}, 300);
		},
	},
};
export default ws;
